package org.springbus.habit.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springbus.habit.emus.ResponseCode;
import org.springbus.habit.entity.ConsumerInfo;
import org.springbus.habit.entity.Role;
import org.springbus.habit.service.ConsumerInfoService;
import org.springbus.habit.service.RoleService;
import org.springbus.habit.web.entity.AllRoleEntity;
import org.springbus.habit.web.entity.AssignRoleEntity;
import org.springbus.habit.web.response.CommonResponse;
import org.springbus.habit.web.response.ConsumerResponse;
import org.springbus.habit.web.response.PageResponse;
import org.springbus.habit.web.response.RoleResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 客户信息表 前端控制器
 * </p>
 *
 * @author Mr.Han
 * @since 2024-05-16
 */
@Tag(name = "客户信息表")
@RestController
public class ConsumerInfoController {

    @Resource
    private ConsumerInfoService consumerInfoService;

    @Resource
    private RoleService roleService;

    @GetMapping("/admin/acl/user/{page}/{limit}")
    @Operation(summary = "分页查询客户信息")
    public PageResponse<ConsumerResponse> getPageList(@Parameter(description = "当前页码", required = true) @PathVariable Long page,
                                                      @Parameter(description = "每页条数", required = true) @PathVariable Long limit,
                                                      @Parameter(description = "用户名称") String username) {
        Page<ConsumerInfo> infoPage = consumerInfoService.page(new Page<>(page, limit),
                new QueryWrapper<ConsumerInfo>().likeRight(StringUtils.isNoneBlank(username),"username", username)
                        .eq("deleted", false));
        if (Objects.isNull(infoPage) || infoPage.getRecords().isEmpty()) {
            return new PageResponse<>(Lists.newArrayList(), 0L);
        }
        List<ConsumerResponse> list = infoPage.getRecords().stream()
                .map(info -> {
                    ConsumerResponse response = new ConsumerResponse();
                    BeanUtils.copyProperties(info, response);
                    response.setGmtCreate(info.getGmtCreate());
                    response.setGmtModified(info.getGmtModified());
                    response.setStatus(info.getStatus() == 1 ? "有效" : "无效");
                    return response;
                }).toList();
        return new PageResponse<>(list, infoPage.getTotal());
    }

    @GetMapping("/admin/acl/user/toAssign/{userId}")
    @Operation(summary = "根据用户id查询用户绑定的角色以及所有角色")
    public CommonResponse<RoleResponse> getRoles(@Parameter(description = "用户ID", required = true)@PathVariable String userId) {
        List<Role> allRoles = roleService.list(new QueryWrapper<Role>().eq("deleted", false));
        ConsumerInfo info = consumerInfoService.getOne(new QueryWrapper<ConsumerInfo>()
                .eq("id", userId).eq("deleted", false));
        RoleResponse response = new RoleResponse();
        List<AssignRoleEntity> assignRoles = Lists.newArrayList();
        List<AllRoleEntity> allRolesList = Optional.ofNullable(allRoles).orElse(Lists.newArrayList())
                .stream().map(e -> {
                    AllRoleEntity entity = new AllRoleEntity();
                    BeanUtils.copyProperties(e, entity);
                    return entity;
                }).toList();
        if (Objects.nonNull(info) && StringUtils.isNoneBlank(info.getRoleIds())) {
            List<Long> list = getRoleIdList(info.getRoleIds());
            List<Role> roles = roleService.listByIds(list);
            assignRoles = Optional.ofNullable(roles).orElse(Lists.newArrayList())
                    .stream().map(e -> {
                        AssignRoleEntity entity = new AssignRoleEntity();
                        BeanUtils.copyProperties(e, entity);
                        return entity;
                    }).toList();
        }
        response.setAllRolesList(allRolesList);
        response.setAssignRoles(assignRoles);
        return new CommonResponse<>(response);
    }

    @PostMapping("/admin/acl/user/doAssign")
    @Operation(summary = "修改用户角色")
    public CommonResponse<Boolean> saveUserRoles(@Parameter(description = "用户ID", required = true)String userId,
                                                 @Parameter(description = "角色IDS", required = true)String roleId) {
        ConsumerInfo entity = new ConsumerInfo();
        entity.setRoleIds(roleId);
        entity.setGmtModified(new Date());
        consumerInfoService.update(entity,new QueryWrapper<ConsumerInfo>().eq("id",userId)
                .eq("deleted",false));
        return new CommonResponse<>(true);
    }

    @PutMapping("/admin/acl/user/update")
    @Operation(summary = "修改客户信息")
    public CommonResponse<Boolean> updateUser(@Parameter(description = "客户信息", required = true)@RequestBody ConsumerInfo info) {
        if (Objects.isNull(info) || Objects.isNull(info.getId())){
            return new CommonResponse<>(ResponseCode.SYSTEM_ERROR);
        };
        info.setGmtModified(new Date());
        consumerInfoService.updateById(info);
        return new CommonResponse<>(true);
    }

    @PostMapping("/admin/acl/user/save")
    @Operation(summary = "保存客户信息")
    public CommonResponse<Boolean> saveUser(@Parameter(description = "客户信息", required = true)@RequestBody ConsumerInfo info) {
        if (Objects.isNull(info)){
            return new CommonResponse<>(ResponseCode.SYSTEM_ERROR);
        }
        info.setGmtCreate(new Date());
        consumerInfoService.save(info);
        return new CommonResponse<>(true);
    }

    @DeleteMapping("/admin/acl/user/remove/{userId}")
    @Operation(summary = "删除客户信息")
    public CommonResponse<Boolean> removeUser(@Parameter(description = "用户ID", required = true)@PathVariable String userId) {
        consumerInfoService.update(new ConsumerInfo().setDeleted(true).setGmtModified(new Date()),new QueryWrapper<ConsumerInfo>()
                .eq("id",userId).eq("deleted", false));
        return new CommonResponse<>(true);
    }

    @DeleteMapping("/admin/acl/user/batchRemove")
    @Operation(summary = "批量删除客户信息")
    public CommonResponse<Boolean> removeUser(@Parameter(description = "用户ID", required = true)@RequestBody ArrayList<String> userIds) {
        consumerInfoService.updateBatchById(userIds.stream().map(Long::valueOf).map(e -> {
            ConsumerInfo entity = new ConsumerInfo();
            entity.setId(e);
            entity.setDeleted(true);
            entity.setGmtModified(new Date());
            return entity;
        }).toList());
        return new CommonResponse<>(true);
    }

    private List<Long> getRoleIdList(String roleIds) {
        return Arrays.stream(Optional.ofNullable(roleIds).orElse("").split(",")).map(Long::valueOf).toList();
    }
}
